package com.hs.pk.berth.job;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hs.pk.berth.bean.Road;
import com.hs.pk.berth.constant.RedisConstant;
import com.hs.pk.berth.constant.RoadStatus;
import com.hs.pk.berth.service.IRoadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lhj
 * @date 2022 - 07 - 21
 * @desc
 */
@Slf4j
@Component
public class MaxBerth {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IRoadService roadService;

    @Scheduled(cron = "0 0/59 * * * ?")
    public void execute() {
        //预热路段名与经纬度
        Long addedNum1 = redisTemplate.opsForGeo().add("geo", new Point(114.037608,22.616739), "妈湾1路");
        Long addedNum2 = redisTemplate.opsForGeo().add("geo", new Point(114.01666,22.605616), "皇岗1路");
        Long addedNum3 = redisTemplate.opsForGeo().add("geo", new Point(114.006419,22.596441), "翻身1路");
        Long addedNum4 = redisTemplate.opsForGeo().add("geo", new Point(114.019247,22.643312), "清湖1路");
        Long addedNum5 = redisTemplate.opsForGeo().add("geo", new Point(114.049179,22.607217), "布吉1路");

        //1. 查询未启用的路段
        List<Road> road = roadService.findRoadByStatus(RoadStatus.NO_ENABLED);

        //2. 判断
        if (!CollectionUtils.isEmpty(road)) {
            //2.1 不为空，缓存到redis当中
            initStorage(road);
            //2.2.1 获取查询数据库得到的秒杀商品id集合
            List<Long> idList = road.stream()
                    .map(Road::getId)
                    .collect(Collectors.toList());

            //2.2.2 修改road表中路段的状态
            LambdaUpdateWrapper<Road> qw = Wrappers.lambdaUpdate(Road.class);
            qw.set(Road::getStatus, RoadStatus.ENABLED);
            qw.in(Road::getId, idList);
            roadService.update(qw);
        }
    }

    //
    private void initStorage(List<Road> road) {
        road.forEach(r -> {
            Long roadId = r.getId();
            Integer maxBerthNum = r.getImitBerthNum();
            log.info("道路id为：{},最大泊车位为：{}", roadId, maxBerthNum);
            for (Integer i = 0; i < maxBerthNum; i++) {
                redisTemplate.opsForList().leftPush(RedisConstant.BERTH_COUNT + roadId, roadId);
            }
        });
    }
}
